import os
import traceback

import yaml

from config.operationConfig import OperationConfig
from config.setting import FILE_PATH
from utils.logging_tool.recordlog import logs


class ReadYamlData:
    """ 读写extract.yaml数据 """

    def __init__(self, yaml_file=None):
        if yaml_file is not None:
            self.yaml_file = yaml_file
        # else:
        # logs.error('请检查yaml数据是否存在')
        self.conf = OperationConfig()
        self.yaml_data = None

    def get_yaml_data(self):
        """
        获取yaml数据,获取的是全部数据
        :param file: YAML文件
        :return: 返回list
        """
        try:
            with open(self.yaml_file, 'r', encoding='utf-8') as f:
                self.yaml_data = yaml.safe_load(f)
                return self.yaml_data
        except Exception:
            logs.error(str(traceback.format_exc()))

    def write_yaml_data(self, value):
        """
        写入extract.yaml文件,用于接口关联
        :param value: 写入数据，必须用dict 类型
        :return:
        """
        file = None
        file_path = FILE_PATH['EXTRACT']
        if not os.path.exists(file_path):
            with open(file_path, 'w'):
                pass
        try:
            file = open(file_path, 'a', encoding='utf-8')
            if isinstance(value, dict):
                write_data = yaml.dump(value, allow_unicode=True, sort_keys=False)
                file.write(write_data)
            else:
                logs.info('写入[extract.yaml]的数据必须为dict格式')
        except Exception:
            logs.error(str(traceback.format_exc()))
        finally:
            file.close()

    def clear_yaml_data(self):
        """
        清空extract.yaml文件数据
        :return:
        """
        with open(FILE_PATH['EXTRACT'], 'w') as f:
            f.truncate()

    def get_extract_yaml(self, node_name, second_node_name=None):
        """
        用于读取接口提取的变量值(extract.yaml)，根据需要提取数据
        :param node_name: 第一个节点的值: 第一级key值
        :param second_node_name: 第二个节点的值：下一级key值
        :return:
        """
        if os.path.exists(FILE_PATH['EXTRACT']):
            pass
        else:
            logs.error('extract.yaml不存在')
            file = open(FILE_PATH['EXTRACT'], 'w')
            file.close()
            logs.info('extract.yaml创建成功！')
        try:
            with open(FILE_PATH['EXTRACT'], 'r', encoding='utf-8') as rf:
                ext_data = yaml.safe_load(rf)
                if second_node_name is None:
                    return ext_data[node_name]
                else:
                    return ext_data[node_name][second_node_name]
        except yaml.YAMLError as e:
            logs.error(f'读取【extract.yaml】文件失败，请检查格式，{e} ')
        except Exception as e:
            logs.error(f"【extract.yaml】没有找到：{node_name},--%s" % e)
